package com.ruoyi.keep.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.keep.domain.*;
import com.ruoyi.keep.mapper.*;

import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.keep.domain.OrderDetail;
import com.ruoyi.keep.domain.SelfishCourse;
import com.ruoyi.keep.domain.TeamClass;
import com.ruoyi.keep.mapper.OrderDetailMapper;
import com.ruoyi.keep.mapper.SelfishCourseMapper;
import com.ruoyi.keep.mapper.TeamClassMapper;

import com.ruoyi.score.domain.Goods;
import com.ruoyi.score.domain.Score;
import com.ruoyi.score.mapper.GoodsMapper;
import com.ruoyi.score.mapper.ScoreMapper;
import com.ruoyi.score.service.IScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.keep.service.IOrderService;

/**
 * 订单Service业务层处理
 *
 * @author wangziyang
 * @date 2024-08-13
 */
@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private TeamClassMapper teamClassMapper;
    @Autowired
    private SelfishCourseMapper selfishCourseMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private DeliveryAddressMapper deliveryAddressMapper;
    @Autowired
    private ReservationMapper reservationMapper;
    @Autowired
    private IScoreService iScoreService;



    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public Order selectOrderById(Long id) {
        return orderMapper.selectOrderById(id);
    }

    /**
     * 查询订单列表
     *
     * @param order 订单
     * @return 订单
     */
    @Override
    public List<Order> selectOrderList(Order order) {
        return orderMapper.selectOrderList(order);
    }

    /**
     * 新增订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int insertOrder(Order order) {
        return orderMapper.insertOrder(order);
    }

    /**
     * 修改订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int updateOrder(Order order) {
        return orderMapper.updateOrder(order);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderByIds(Long[] ids) {
        return orderMapper.deleteOrderByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderById(Long id) {
        return orderMapper.deleteOrderById(id);
    }

    /*
     * 小程序端条件查询全部订单
     * */
    @Override
    public List<Order> selectOrderLists(Order order) {
        //id判断条件--搜索条件是id，则关闭名称搜索，如果搜索条件是名称，则关闭id
        boolean idIf=false;
        //条件查询--id（与商品名称共用一个），订单类型，订单状态
        List<Order> orderList=new ArrayList<>();
        if (order.getOrderStatus()!=null && order.getOrderStatus()==4){
            orderList = orderMapper.selectList(new QueryWrapper<Order>().
                    like(order.getOrderGoodsName() != "", "id", order.getOrderGoodsName()).
                    like( order.getOrderType() != null, "order_type", order.getOrderType()).
                    like(order.getOrderStatus() !=null, "order_status", 3).or().
                    like(order.getOrderStatus() !=null, "order_status", 4));
        }else {
            orderList = orderMapper.selectList(new QueryWrapper<Order>().
                    like(order.getOrderGoodsName() != "", "id", order.getOrderGoodsName()).
                    like( order.getOrderType() != null, "order_type", order.getOrderType()).
                    like(order.getOrderStatus() !=null, "order_status", order.getOrderStatus()));
        }
        //用于判断的list集合
        List<Order> orderListIf=orderMapper.selectList(new QueryWrapper<Order>().
                like(order.getOrderType() != null, "order_type", order.getOrderType()).or().
                like(order.getOrderStatus() != null, "order_status", order.getOrderStatus()));
        //搜索条件不是id，是商品名称
        if (orderList.isEmpty() || (orderList.size()==orderListIf.size())){
            idIf=true;
            orderList=orderListIf;
        }
        Iterator<Order> iterator = orderList.iterator();
        while (iterator.hasNext()) {
            Order orders = iterator.next();
            try {
                // 获取课程或商品id
                orders.setOrderDetailId(orderDetailMapper.selectOrderDetailByOrderId(orders.getId()).getOrderDetailId());
                // 判断是课程还是商品
                if (orders.getOrderType() == 0) {
                    TeamClass teamClass=teamClassMapper.selectOne(new QueryWrapper<TeamClass>().
                            like("id", orders.getOrderDetailId()).
                            like(idIf, "class_name", order.getOrderGoodsName()));
                    if (teamClass != null){
                        orders.setTeamClass(teamClass);
                    }else{
                        iterator.remove();
                    }
                } else if (orders.getOrderType() == 1) {
                    SelfishCourse selfishCourse=selfishCourseMapper.selectOne(new QueryWrapper<SelfishCourse>().
                            like("id", orders.getOrderDetailId()).
                            like(idIf, "name", order.getOrderGoodsName()));
                    if (selfishCourse != null){
                        orders.setSelfishCourse(selfishCourse);
                    }else{
                        iterator.remove();
                    }
                } else if (orders.getOrderType() == 2) {
                    Goods good = goodsMapper.selectOne(new QueryWrapper<Goods>().
                            like("id",orders.getOrderDetailId()).
                            like(idIf, "goods_name", order.getOrderGoodsName()));
                    if (good != null){
                        DeliveryAddress deliveryAddress =deliveryAddressMapper.selectOne(new QueryWrapper<DeliveryAddress>().eq("id",orders.getAddressId()));
                        orders.setDeliveryAddress(deliveryAddress);
                        orders.setOrderGoodsName(good.getGoodsName());
                        orders.setGoods(good);
                    }else {
                        iterator.remove();
                    }
                }
            } catch (Exception e) {
                System.out.println("有的数据库不存在: " + e.getMessage());
                // 可以在这里选择是否删除该订单
                iterator.remove();
            }
        }
        return orderList;
    }


    /*
     * 订单申请退款，区分是预约还是积分兑换
     * */
    @Override
    public int updateOrderStatus(Order order) {
        Long id=order.getId();
//        当订单是预约的时候，需要更改预约状态
        if (order.getOrderType() !=2){
            int j=reservationMapper.update(null,new UpdateWrapper<Reservation>().eq("order_id",id).set("reservation_status",2));
            int k=orderMapper.update(order,new UpdateWrapper<Order>().eq("id",id).set("order_status",3));
            return k+j;
        }
        int i=orderMapper.update(order,new UpdateWrapper<Order>().eq("id",id).set("order_status",3));
        return i;
    }



    /**
     * 获取积分兑换订单
     * */
    @Override
    public List<Order> getGoodsOrder(Map<String, Object> map) {
        List<Order> orders = orderMapper.selectGoodsOrder(map);
        return orders;
    }

    /**
     * 新增积分兑换订单
     * */
    @Override
    public int insertScoreOrder(Map<String, Object> map) {
        Long userId = ((Integer) map.get("userId")).longValue();
        Integer orderPrice = Integer.valueOf((String) map.get("orderPrice"));
        QueryWrapper<Score> wrapper = new QueryWrapper();
        wrapper.eq("user_id", userId);
        Score one = iScoreService.getOne(wrapper);
        if (one.getScoreCurrent() < orderPrice) {
            return -1;//积分不足
        }
        Date date = new Date();
        Long orderStatus = ((Integer) map.get("orderStatus")).longValue();
        Long addressId = ((Integer) map.get("addressId")).longValue();
        Long shopId = Long.valueOf((String) map.get("shopId"));

        Order order = new Order(null, date, date, userId, orderPrice.doubleValue(), null, 2L,
                orderStatus, addressId);
        orderMapper.insertOrder(order);
        orderDetailMapper.insert(new OrderDetail(order.getId(), shopId, null, null));
        Long score = orderPrice.longValue();
        int i = iScoreService.signIn(userId, "积分兑换", score * -1, 0);
        return order.getId().intValue();
    }

    @Override
    public List<Order> selectOrderDetailById(Long id) {
        return orderMapper.selectOrderDetailById(id);
    }

}
